import { FormFactory } from '@/pages/form-model/model/formFactory';
import { FormProperty } from '@/pages/form-model/model/formProperty';
import { BehaviorSubject } from 'rxjs';
import { FormItemScheme } from '../interface';
import { FormModel } from './form.model';

export class ObjectOperation extends FormProperty {
  properties: FormProperty[];
  showProperties: FormProperty[];
  $showProperties = new BehaviorSubject<FormProperty[]>([]);

  constructor(scheme?: FormItemScheme, namePath?: string[], root?: FormModel) {
    super(scheme, namePath, root);
    this.$showProperties.subscribe((res) => {
      this.showProperties = res;
    });
  }

  createProperties(properties, namePath: string[], root) {
    this.properties = properties.map((item) => {
      return FormFactory.createProperty(item, namePath, root);
    });
    this.$showProperties.next(this.properties);
  }

  delProperty(property: FormProperty) {
    this.$showProperties.next(
      this.showProperties.filter((item) => item !== property),
    );
  }

  addProperty(property: FormProperty) {
    const newProperties = this.properties.reduce((p, n) => {
      if (n === property || this.showProperties.some((item) => item === n)) {
        return [...p, n];
      }
      return p;
    }, []);
    this.$showProperties.next(newProperties);
  }
}
export class ObjectProperty extends ObjectOperation {
  constructor(
    scheme: FormItemScheme,
    namePath: string[] = [],
    root?: FormModel,
  ) {
    const { properties, name } = scheme;
    const path = [...namePath, name] as string[];
    super(scheme, path, root);
    this.createProperties(properties, path, root);
  }
}
